<template> 
    <div> 
        <Row style="margin:5px 0px 10px 5px" >
            <i-col span="2" >
                <Button  size="default"  type="primary" @click="btn_refresh">刷新</Button>
            </i-col>
		</Row>
        <i-table size="default"   border stripe  :columns="format" :data="show_list" :height="sharedState.tableHeight" >
            <template slot-scope="{ row, index }" slot="action">
                <Dropdown>
                    <a href="javascript:void(0)">
                        <Icon type="ios-create-outline" size="30" />
                    </a>
                    <DropdownMenu slot="list" placement="top-end">
                        <DropdownItem><Button  size="default"    @click="btn_edit_vs(index)" long>编辑</Button></DropdownItem>
                        <DropdownItem><Button  size="default"      v-if="has_set_weight(index)"   @click="btn_switch_traffic(index)" long>切流量</Button></DropdownItem>
                        <DropdownItem><Button  size="default"     @click="btn_set_timeout(index)" long>超时设置</Button></DropdownItem>
                        <DropdownItem><Button  size="default"     @click="del_virtual_service(index)" long>删除</Button></DropdownItem>
                    </DropdownMenu>
                </Dropdown>
            </template>
        </i-table >
        <div style="text-align: center;margin-top: 10px;">
            <Page ref="page" :total="total" :page-size="pageSize"  @on-change="changePage" show-total/>
        </div>
        <!--切流量模态框 -->
        <Modal v-model="show_switch_traffic_modal" width="600">
            <p slot="header" style="color:#f60;text-align:center;">
                <span>切流量</span>
            </p>
            <div style="">
                <span>新版流量比例: {{ new_weight }}</span>
                <Form>
                    <Form-Item >
                        <input v-model="new_weight" style="width: 98%" type="range"  max="100" min="0" step="10" />
                    </Form-Item> 
                </Form> 
            </div>
            <div slot="footer">
                <Button  size="default"  type="primary"   @click="submit_switch_traffic">提交</Button>
            </div>
        </Modal>
        <!-- 超时设置模态框 -->
        <Modal v-model="show_set_timeout_modal" width="600">
            <p slot="header" style="color:#f60;text-align:center;">
                {{ vs_name }}<span>超时设置</span>
            </p>
            <div style="">
                <Form ref="timeout" > 
                    <template v-for="item in timeout_list" >
                            <!-- {{index}} -->
                            路由: <Input v-model="item.index" :key="item.index" style="width: 50px"  disabled />
                            
                            超时:<Input v-model="item.timeout" :key="item.timeout" style="width: 100px"  />
                    </template>
                </Form> 
            </div>
            <div slot="footer">
                <Button  size="default"  type="primary"   @click="submit_add_timeout('timeout')">提交</Button>
            </div>
        </Modal>

        <!-- 编辑模态框 -->
        <Modal v-model="show_edit_vs_modal"  class="vertical-center-modal" width="60vw" >
            编辑资源
            <div>
                <yaml-editor  v-model="value"   />
            </div>
            <div style="margin: 5px 0 0 0 ">
                <Row>
                    <i-col span="4"><Button  size="default"  type="primary"    @click="submit_update_vs">更新</Button></i-col>
                    <i-col span="3"><Button  size="default"  type="primary"    @click="cacel_update_vs">取消</Button></i-col>
                </Row>
            </div>
            <div slot="footer" >
            </div>
        </Modal>
    </div>
</template>

<script>
import axios from 'axios';
import {k8s_namespace_post} from '@/api/http'
import { update_vs,
    get_virtual_service_list,
    delete_vs,
    update_timeout,
    get_custom_object,
    update_custom_object
} from  '@/api'
import { show_simple_page } from '@/common/util' 

import { delete_namespace_resource } from '@/common/util.js'
import YamlEditor  from '@/lib/editor/yamlEditor';
import store from '@/store'

export default {
    components: { YamlEditor },
    data() {
        return {
            sharedState: store.state,
            format: [
                {
                    title: '名字',key: 'name',align: 'center',width: 150,
                },
                {
                    title: '命名空间',key: 'namespace',align: 'center',width: 170,
                },
                {
                    title: '路由',key: 'http',align: 'left',width: 600,resizable: true,
                    render: (h, params) => {
                        let https=params.row.http
                        console.log(https)
                        let value=''
                        for(let i=0;i< https.length;i++){
                            let http = https[i]
                            let path = ''
                            let match = http['match']
                            if(match){
                                // path = JSON.stringify(http['match'])
                                for(let m = 0;m< match.length;m++){
                                    path += JSON.stringify(match[m])
                                    if(m != match.length-1){
                                        path+='\n      '
                                    }
                                }
                            }else{
                                path='无'
                            }
                            let timeout =  http['timeout']
                            if(timeout==null){
                                timeout = '无'
                            }
                            let route = http['route']
                            let myroute = ''
                            for(let j = 0;j<route.length;j++ ){
                                let destination = route[j]['destination']
                                let host = destination['host']
                                let port_number = null
                                let endpoint = ''
                                if(destination['port']){
                                    port_number = destination['port']['number']
                                    endpoint = host+':'+port_number
                                }else {
                                    endpoint = host
                                }
                                
                                let subset = destination['subset']
                                if(subset==null){
                                    subset = '无'
                                }
                                let weight = route[j]['weight']
                                if(weight==null){
                                    weight = '无'
                                }
                                let item = "路由到: "+endpoint+"\n"+"    版本: "+subset+"   流量比例: "+weight
                                myroute += item
                                if(j != route.length-1){
                                    myroute+='\n'
                                }
                            } 
                            let http_item = "匹配项: "+path+"\n"+myroute+"\n超时: "+timeout
                            value += http_item
                            if(i != https.length-1){
                                value += "\n\n"
                            }
                        }
                        return h('pre',value)
                    }
                },
                {
                    title: '绑定网关',key: 'gateways',align: 'center',width: 200,
                    render: (h, params) => {
                        let value  = params.row.gateways
                        console.log(value)
                        if(value == null || value == undefined ) {
                            return  h('p','无')
                        }else{
                            return h('p',value)
                        } 
                    }
                },
                {
                    title: '主机',key: 'hosts',align: 'center',width: 200,
                },
                {
                    title: '创建时间',key: 'create_time',align: 'center',width: 150,
                },
                {
                    title: '',slot: 'action',align: 'center',width: 150,fixed:'right',
                }

            ],
            total_list: [],
            show_list: [],
            // 分页
            total: 0,
            pageSize: 10,
            show_switch_traffic_modal: false,
            new_weight: 10,
            vs_name: '',
            // 设置超时
            timeout_list: null,
            show_set_timeout_modal: false,
            timeout_rules: {

            },
            // 编辑
            show_edit_vs_modal:false,
            value: '',
        }
    },
    methods: {
        handleLink(params){
            let cluster = localStorage.getItem('currentCluster')
            const { href } = this.$router.resolve({
                name: 'virtualServiceDetail'
            });
            window.open(href+"?name="+params.row.name+"&cluster="+cluster+"&namespace="+params.row.namespace, '_blank');
        },
        btn_refresh(){
            this.refresh()
        },
        changePage(index) {
            let _start = (index -1) * this.pageSize
            let _end = index * this.pageSize
            this.show_list = this.total_list.slice(_start,_end)
        },
        submit_update_vs(){
            console.log(this.value+update_custom_object) 
            let name = this.vs_name
            let data = {
                "name": name,
                "plural": "virtualservices",
                "body": this.value,
            }
            k8s_namespace_post(update_custom_object,data).then(response=>{
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok') != -1) {
                    this.$Message.success('更新资源成功')
                    this.show_edit_vs_modal = false
                    this.refresh()
                }else {
                    alert(info)
                }
            })
        },
        cacel_update_vs(){
            this.show_edit_vs_modal=false
        },
        // 
        btn_edit_vs(index){
            let name = this.show_list[index].name
            this.vs_name = name
            let data = {
                "name": name,
                "plural": "virtualservices",
            }
            let headers = {}
            let cluster = localStorage.getItem('currentCluster')
            let namespace = localStorage.getItem('currentNameSpace')
            headers["cluster_name"] =  cluster 
            data["namespace"] = namespace
            axios({
                method:'post',
                url:get_custom_object,
                data:JSON.stringify(data),
                headers:headers,
                timeout: 2000,
                responseType: 'blob',
            }).then(res =>{
                if (typeof FileReader === "undefined") { 
                    this.$Message.error("您的浏览器不支持读取文件")
                    return;
                }
                let _that = this;
                let reader = new FileReader();
                reader.readAsText(res.data);
                reader.onloadend = function (e) { 
                    _that.value=e.target.result;
                    _that.show_edit_vs_modal = true;
                }
            }).catch(error => {
                console.log(error)
                this.$Message.error("请求异常,查看console")
            })

        },
        submit_add_timeout(name){
            console.log(name)
            // 校验数据
            let timeout_list =this.timeout_list
            for(let i=0;i<timeout_list.length;i++){
                let timeout = timeout_list[i]['timeout']
                if ( /^[0-9]*$/.test(timeout)==true){
                    this.$Message.error("超时必须带上单位，比如4秒4s")
                    return
                }
                if(timeout == null ||timeout== '') {
                    this.$Message.error("timeout 不允许为空")
                    return
                }
            }

            let vs_name = this.vs_name
            let data={"name":vs_name,"timeout_list":timeout_list}
            k8s_namespace_post(update_timeout,data).then( (response) => {
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok') != -1) {
                    this.$Message.success('更新超时设置成功')
                    this.show_set_timeout_modal = false
                    this.refresh()
                }else {
                    alert(info)
                }
            })
        },
        btn_set_timeout(index){
            let http = this.show_list[index].http
            this.timeout_list = []
            for(let i = 0;i< http.length;i++){
                let timeout = http[i]['timeout']
                let item = null
                if(timeout == undefined){
                    item = {"index":i,"timeout":null}
                }else {
                    item = {"index":i,"timeout":timeout}
                }   
                this.timeout_list[i]=item
               
            }
            console.log(JSON.stringify(this.timeout_list))
            let vs_name = this.show_list[index].name
            this.vs_name = vs_name
            this.show_set_timeout_modal = true
        },
        // 检测是否含有版本设置 weight
        has_set_weight(index){
            let labels = JSON.stringify(this.show_list[index].http)
            if(labels.indexOf('weight') == -1){
                return false
            }  
            return true
        },
        // 点击切流量
        btn_switch_traffic(index){
            let namespace = localStorage.getItem('currentNameSpace')
            if (namespace =='' || namespace == 'all'){
                alert("去选择具体的namespace")
                return
            }
            let http = this.show_list[index].http
            if(http.length > 1) {
                alert("多个路由条目,暂不支持")
                return
            }
            let routes = http[0].route
            let has_new = false
            if(routes.length > 0) {
                for(let i=0;i<routes.length;i++) {
                    let subset = routes[i].destination.subset
                    if(subset=="new"){
                        has_new = true
                        this.new_weight =  routes[i].weight
                    }
                }
            }
            if(!has_new){
                alert("没发现版本设置,请检查route是否有新版本")
                return
            }
            let vs_name = this.show_list[index].name
            this.vs_name = vs_name
            this.show_switch_traffic_modal = true
        },
        // 提交切流量
        submit_switch_traffic(){
            let data = {"vs_name":this.vs_name,'new_weight':this.new_weight}
            k8s_namespace_post(update_vs,data).then( (response) => {
                let info = JSON.stringify(response.data)
                if(info.indexOf(this.new_weight) != -1) {
                    this.$Message.success('切换流量成功')
                    this.show_switch_traffic_modal = false
                    this.refresh()
                }else {
                    alert(info)
                }
            })
        },

        del_virtual_service(index){
            let name = this.show_list[index].name
            let result = confirm("确定要删除"+name+"吗?")
            if(result == false) return 
            let namespace = this.show_list[index].namespace
            delete_namespace_resource(namespace,name,delete_vs)
            this.refresh()
        },
        refresh() {
            k8s_namespace_post(get_virtual_service_list).then( (response) => {
                show_simple_page(this,response)
            })
        }
    },
    mounted: function() {
        setTimeout(() =>{
            this.refresh();
        },200); 
    }
}
</script>
<style lang="less">
    pre {
        white-space: pre-wrap!important;
        word-wrap: break-word!important;
        *white-space:normal!important;
    }
    .vertical-center-modal{
        display: flex;
        align-items: center;
        justify-content: center;
        .ivu-modal{
            top: 0;
        }
    }
</style>